# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

from expect_tests.type_definitions import Handler, Test, MultiTest


class ListHandler(Handler):
  """List all of the tests instead of running them."""
  SKIP_RUNLOOP = True

  # Used to collect all bare test names for command line test name completion.
  COMPLETION_LIST = None

  class ResultStageHandler(Handler.ResultStageHandler):
    @staticmethod
    def handle_Test(test):
      if ListHandler.COMPLETION_LIST is not None:
        ListHandler.COMPLETION_LIST.append(test.name)
      else:
        print test.name

    @staticmethod
    def handle_MultiTest(multi_test):
      print 'MultiTestInfo(%r, atomic=%r)' % (
        multi_test.name, multi_test.atomic)
      for test in multi_test.tests:
        if ListHandler.COMPLETION_LIST is not None:
          ListHandler.COMPLETION_LIST.append(test.name)
        else:
          print '|', test.name

    # TODO(iannucci): group tests by dir?
    # TODO(iannucci): print more data about the test in verbose mode?

  @classmethod
  def gen_stage_loop(cls, _opts, tests, put_next_stage, _put_result_stage):
    """Called in the GenStage portion of the pipeline.

    @param opts: Parsed CLI options
    @param tests:
        Iterable of type_definitions.Test or type_definitions.MultiTest
        objects.
    @param put_next_stage:
        Function to push an object to the next stage of the pipeline (RunStage).
        Note that you should push the item you got from |tests|, not the
        subtests, in the case that the item is a MultiTest.
    @param put_result_stage:
        Function to push an object to the result stage of the pipeline.
    """
    for test in tests:
      if isinstance(test, (Test, MultiTest)):
        test = test.get_info()

      else:
        raise TypeError('ListHandler.gen_stage_loop cannot handle type %s'
                        % test.__class__.__name__)
      put_next_stage(test)
